﻿using CSRedis;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Rw.Core.Common;
using WH.Common.Constant;
using WH.Common.DbConfig;
using WH.Common.DbConfig.Model;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Reflection;

namespace WH.WebApi.Controllers.Systems
{
    /// <summary>
    /// 系统设置
    /// </summary>
    [Authorize, Route("SysConfig"), ApiController]
    public class SysConfigController : BaseController
    {

        private readonly IServer _server;

        private readonly IConfiguration _configuration;

        /// <summary>
        /// 系统设置
        /// </summary>
        public SysConfigController(IServer server, IConfiguration configuration)
        {
            _server = server;
            _configuration = configuration;
        }

        /// <summary>
        /// 设置配置
        /// </summary>
        /// <param name="inputs"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultResponse> SaveAsync([FromBody] List<ConfigInputDto> inputs)
        {
            foreach (ConfigInputDto input in inputs)
            {
                if (input.IsEnable is null)
                {
                    input.IsEnable = true;
                }
            }

            var res = await new DatabaseConfigurationProvider().SaveAsync(inputs, _configuration);

            return res > 0 ? Success() : Error();
        }

        /// <summary>
        /// 删除配置
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<ResultResponse> DeleteAsync([FromBody] List<string> ids)
        {
            var res = await new DatabaseConfigurationProvider().DeleteAsync(ids);
            return res > 0 ? Success() : Error();
        }

        /// <summary>
        /// 获取配置树
        /// </summary>
        /// <returns></returns>
        [HttpGet("Tree")]
        public async Task<ResultResponse<List<ConfigOutputDto>>> GetTreeAsync(string? parentId)
        {
            var data = new DatabaseConfigurationProvider();

            parentId = string.IsNullOrWhiteSpace(parentId) ? BusinessFunction.TopParentId : parentId;

            return await Task.FromResult(Success(data.GetTrees(parentId)));
        }


        /// <summary>
        /// 获取配置列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("List")]
        public async Task<ResultResponse<IList<ConfigOutputDto>>> GetListAsync()
        {
            var data = new DatabaseConfigurationProvider();

            IList<ConfigOutputDto> list = data.GetList();

            return await Task.FromResult(Success(list));
        }


        /// <summary>
        /// 获取配置项
        /// </summary>
        /// <returns></returns>
        [HttpGet("Link")]
        public async Task<ResultResponse<ConfigOutputDto?>> GetLinkAsync([FromQuery] string link)
        {
            var data = new DatabaseConfigurationProvider();

            var res = data[link];

            if (res is not null)
            {
                res.Children = res.Children?.Where(x => x.IsEnable).ToList();
            }
            return await Task.FromResult(Success(res));
        }



        /// <summary>
        /// 获取匿名配置项
        /// </summary>
        /// <returns></returns>
        [HttpGet("Anonymous")]
        [AllowAnonymous]
        public async Task<ResultResponse<Dictionary<string, string?>>> GetAnonymous()
        {
            var data = new DatabaseConfigurationProvider();

            var logo = data.Appsettings.FirstOrDefault(x => x.Key == "web_logo");
            var name = data.Appsettings.FirstOrDefault(x => x.Key == "web_name");// data.Appsettings["web_name"];

            var dic = new Dictionary<string, string?>();

            dic.Add("web_logo", logo?.Value);
            dic.Add("web_name", name?.Value);

            return await Task.FromResult(Success(dic));
        }

        /// <summary>
        /// 数据库地址测试
        /// </summary>
        /// <returns></returns>
        [HttpPost("DbPing")]
        public ResultResponse DbPing()
        {
            var data = new DatabaseConfigurationProvider();

            var dbTypeConfig = data["DbType"];
            var connectionStringConfig = data["ConnectionString"];

            if (dbTypeConfig is null || connectionStringConfig is null)
            {
                return Error("数据库配置不能为空，请检查");
            }

            var db = new SqlSugarClient(new ConnectionConfig
            {
                ConnectionString = connectionStringConfig.Value,
                DbType = (SqlSugar.DbType)int.Parse(dbTypeConfig.Value ?? "0"),
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute
            });

            var isValid = db.Ado.IsValidConnection();

            return isValid ? Success("数据库连接成功") : Error("数据库连接失败");
        }

        /// <summary>
        /// Redis地址测试
        /// </summary>
        /// <returns></returns>
        [HttpPost("RedisPing")]
        public ResultResponse RedisPing()
        {
            var data = new DatabaseConfigurationProvider();

            var server = data["RedisOptions:Default:Server"];
            var port = data["RedisOptions:Default:Port"];
            var defaultDb = data["RedisOptions:Default:DefaultDatabase"];
            var passowrd = data["RedisOptions:Default:Password"];

            if (server is null || port is null || defaultDb is null)
            {
                return Error("Redis配置不能为空，请检查");
            }

            var redis = new CSRedisClient($"{server.Value}:{port.Value},password={passowrd?.Value ?? string.Empty},defaultDatabase={defaultDb.Value}");

            var isValid = false;

            try
            {
                if (redis.Ping())
                {
                    isValid = true;
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                redis.Dispose();
            }

            return isValid ? Success("Redis连接成功") : Error("Redis连接失败");
        }
        /// <summary>
        /// 获取当前版本号
        /// </summary>
        /// <returns></returns>
        [HttpGet("Version")]
        public ResultResponse<string?> GetVersion()
        {
            var version = Assembly.GetEntryAssembly()?.GetCustomAttribute<AssemblyFileVersionAttribute>()?.Version;

            return Success<string?>(version);
        }
    }
}
